package com.xxxx.yoyo.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.xxxx.yoyo.bean.Admin;


@WebFilter("/admin/*")
public class AdminLoginFilter implements Filter {

    /**
     * Default constructor. 
     */
    public AdminLoginFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * 放行（允许）请求
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		//把request强转为HIttpServletRequest类型
		HttpServletRequest req = (HttpServletRequest)request;
		//获取请求的地址
		String path = req.getServletPath();
		
		if (path.contains("/css/") || path.contains("/js") || path.contains("/layui/")
				|| path.contains("/img/") || path.equals("/admin/login.jsp")
				|| path.equals("/admin/login")) {
			chain.doFilter(request,response);
		}else {
			//获取session,查看用户是否登录
			HttpSession session = req.getSession();
			Admin admin = (Admin)session.getAttribute ("admin");
			if(admin != null){//说明用户登录了，放行
				chain.doFilter(request, response);
			}else {//管理员没有登录，重定向到登录页面
				HttpServletResponse resp = (HttpServletResponse)response;
				resp.sendRedirect ("/YoyoShop/admin/login.jsp");
			}
		}
		// 放行（允许）请求
		//chain.doFilter(request, response);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
